<template>
  <div class="w-card content-box" v-if="!isDetail">
    <div class="title-box">
      <span class="title">售卡管理</span>
      <div style="margin-left: auto;">
        <el-button type="primary" plain @click="importHandle()">导入</el-button>
        <!-- <el-button type="warning" plain @click="exportHandle(1)">导出</el-button> -->
      </div>
    </div>

    <!-- <div class="my-search-box">
      <div>
        <span>结算方式：</span>
        <el-select v-model="searchForm.action" placeholder="请选择" clearable>
          <el-option label="月结" value="1" />
          <el-option label="追加" value="2" />
        </el-select>
      </div>
      <div class="datebox">
        <span>导入时间：</span>
        <el-date-picker v-model="searchForm.date" type="datetimerange" value-format="x" start-placeholder="开始时间"
          end-placeholder="结束时间" />
      </div>
      <div class="f-ml-20">
        <el-button @click="searchHandle" type="primary">查询</el-button>
        <el-button @click="resetHandle">重置</el-button>
      </div>
    </div> -->

    <p style="margin-top: 20px">新导入预览</p>
    <div class="table-box">
      <el-table :max-height="tableHeight" :header-cell-style="{background:'#d6dee5',color:'#000000',fontSize:'14px'}"
        :cell-style="{fontSize:'14px',color:'#7b7b7d'}" :data="importResult" stripe @selection-change="handleSelectionChange">
        <el-table-column type="index" width="55" label="序号" align="center" />
        <!-- <el-table-column type="selection" width="55" /> -->
        <el-table-column prop="fileName" label="文件名称" align="center">
          <template v-slot="scope">
            <el-link type="primary" @click="pageJump('/sellCardsMng/detail',scope.row)">
              {{ scope.row.fileName || '--' }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="month" label="结算月份" align="center">
          <template v-slot="scope">
            {{ scope.row.month }}
          </template>
        </el-table-column>
        <el-table-column prop="action" label="结算方式" align="center">
          <template v-slot="scope">
            {{ action[scope.row.action] }}
          </template>
        </el-table-column>
        <el-table-column prop="totalNum" label="总数" align="center" width="100">
          <template v-slot="scope">
            {{ scope.row.totalNum }}
          </template>
        </el-table-column>
        <el-table-column prop="successNum" label="有效数" align="center" width="100">
          <template v-slot="scope">
            {{ scope.row.successNum  }}
          </template>
        </el-table-column>
        <el-table-column prop="failNum" label="无效数" align="center" width="100">
          <template v-slot="scope">
            {{ scope.row.failNum  }}
          </template>
        </el-table-column>
        <el-table-column prop="totalFee" label="总金额(元)" align="center">
          <template v-slot="scope">
            {{ scope.row.totalFee }}
          </template>
        </el-table-column>
        <el-table-column prop="totalIncome" label="返佣金额(元)" align="center">
          <template v-slot="scope">
            {{ scope.row.totalIncome }}
          </template>
        </el-table-column>
        <el-table-column prop="recordStatus" label="状态" align="center">
          <template v-slot="scope">
            {{ recordStatus[scope.row.recordStatus] }}
          </template>
        </el-table-column>
      </el-table>
      <div class="my-table-footer">
        <div style="margin-left:auto;">
          <el-button @click="handleSettleImportSubmit(2)">取消</el-button>
          <el-button type="primary" @click="handleSettleImportSubmit(1)">确定发放</el-button>
        </div>
      </div>
    </div>

    <p style="margin-top: 50px">历史导入列表</p>
    <div class="table-box">
      <el-table :max-height="tableHeight" :header-cell-style="{background:'#d6dee5',color:'#000000',fontSize:'14px'}"
        :cell-style="{fontSize:'14px',color:'#7b7b7d'}" :data="tableData" stripe @selection-change="handleSelectionChange">
        <el-table-column type="index" width="55" label="序号" align="center" />
        <!-- <el-table-column type="selection" width="55" /> -->
        <el-table-column prop="fileName" label="文件名称" align="center">
          <template v-slot="scope">
            <el-link type="primary" @click="pageJump('/sellCardsMng/detail',scope.row)">
              {{ scope.row.fileName || '--' }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="month" label="结算月份" align="center">
          <template v-slot="scope">
            {{ scope.row.month }}
          </template>
        </el-table-column>
        <el-table-column prop="action" label="结算方式" align="center">
          <template v-slot="scope">
            {{ action[scope.row.action] }}
          </template>
        </el-table-column>
        <el-table-column prop="totalNum" label="总数" align="center" width="100">
          <template v-slot="scope">
            {{ scope.row.totalNum }}
          </template>
        </el-table-column>
        <el-table-column prop="successNum" label="有效数" align="center" width="100">
          <template v-slot="scope">
            {{ scope.row.successNum  }}
          </template>
        </el-table-column>
        <el-table-column prop="failNum" label="无效数" align="center" width="100">
          <template v-slot="scope">
            {{ scope.row.failNum  }}
          </template>
        </el-table-column>
        <el-table-column prop="totalFee" label="总金额(元)" align="center">
          <template v-slot="scope">
            {{ scope.row.totalFee }}
          </template>
        </el-table-column>
        <el-table-column prop="totalIncome" label="返佣金额(元)" align="center">
          <template v-slot="scope">
            {{ scope.row.totalIncome }}
          </template>
        </el-table-column>
        <el-table-column prop="recordStatus" label="状态" align="center">
          <template v-slot="scope">
            {{ recordStatus[scope.row.recordStatus] }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="导入时间" align="center">
          <template v-slot="scope">
            {{ scope.row.createTime ? getDateTime(scope.row.createTime)[6] : '' }}
          </template>
        </el-table-column>
      </el-table>
      <div class="my-table-footer">
        <!-- <div>
            <el-button :disabled="chooseList.length == 0" @click="exportHandle(2)">批量导出</el-button>
          </div> -->
        <el-pagination style="margin-left:auto;" v-model:currentPage="page" v-model:page-size="size"
          :page-sizes="[10, 20, 50, 100]" small :background="true" layout="total, sizes, prev, pager, next, jumper" :total="total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>

    <!-- 导入弹窗 -->
    <File-Upload ref="uploadRef" v-if="off.upload" :uploadForm="uploadForm" apiName="settleImportTemplete"
      @handleUploadSuccess="importSuccess" @handleUploadCancel="handleUploadCancel">
      <template #slotForm="parent">
        <el-form-item prop="month" label="结算月份" label-width="100">
          <el-date-picker v-model="parent.formData.data.month " type="month" value-format="YYYYMM" placeholder="请选择日期时间"
            style="width: 250px !important" />
        </el-form-item>
        <el-form-item prop="action" label="结算方式" label-width="100">
          <el-select v-model="parent.formData.data.action" placeholder="请选择" clearable style="width: 250px !important">
            <el-option label="月结" value="1" />
            <el-option label="追加" value="2" />
          </el-select>
        </el-form-item>
      </template>
    </File-Upload>
  </div>
  <router-view></router-view>
</template>
  
<script>
import { onMounted, reactive, toRefs, watch, ref, nextTick } from 'vue'
import { getWindowWidthAndHeight, warningDeal, getDateTime, BlobDownLoad, errorDeal, successDeal } from '@/utils/utils'
import { useRoute, useRouter } from 'vue-router'
import FileUpload from '@/components/Upload.vue'
import api from './api'

export default {
  components: { FileUpload },

  setup() {
    const route = useRoute()
    const router = useRouter()

    const uploadRef = ref(null)

    const state = reactive({
      off: {
        upload: false,
      },

      isDetail: false,

      page: 1,
      size: 10,
      total: 0,
      tableHeight: 0,
      tableData: [],
      chooseList: [],

      importResult: [],

      searchForm: {
        "action": "",
        "recordId": "",
        "recordStatus": "3,4",
      },

      recordStatus: {
        '1': '计算中',
        '2': '计算完成',
        '3': '已发放',
        '4': '取消发放',
      },

      action: {
        '1': '月结',
        '2': '追加',
      },

      apiName: '',
      uploadForm: {
        dialogTitle: '导入售卡文件',
        action: '/eas/manage/phone/settle/import-file',
      },
    })

    watch(() => route.path, (newVal, oldVal) => {
      setIsDetail()
    })

    function setIsDetail() {
      state.isDetail = (route.path != '/sellCardsMng')
    }

    function getTableData() {
      const obj = {
        page: state.page,
        size: state.size,
        ...state.searchForm,
        createTimeMin: (state.searchForm.date && state.searchForm.date[0]) ? state.searchForm.date[0] : null,
        createTimeMax: (state.searchForm.date && state.searchForm.date[1]) ? state.searchForm.date[1] : null,
        orderBy: 'id desc',
      }
      api.settleImportList(obj).then(res => {
        if (res.code == '200') {
          state.tableData = res.data.list
          state.total = res.data.total
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function handleCurrentChange(e) {
      state.page = e
      getTableData()
    }

    function handleSizeChange(e) {
      state.size = e
      getTableData()
    }

    function handleSelectionChange(e) {
      state.chooseList = e
    }

    function searchHandle() {
      state.page = 1
      getTableData()
    }

    function resetHandle() {
      state.searchForm = {
        "action": "",
        "recordId": "",
        "recordStatus": "3,4",
      }
      searchHandle()
    }

    // 导入
    function importHandle() {
      state.off.upload = true
      nextTick(() => {
        uploadRef.value.off.dialog = true
      })
    }

    //导入成功
    function importSuccess(data) {
      state.page = 1
      getSettleImportResult(data.recordId)
    }

    const handleUploadCancel = () => {
      state.off.upload = false
    }

    function exportHandle() {
      let obj = {
        page: state.page,
        size: state.size,
        ...state.searchForm,
        createTimeMin: (state.searchForm.date && state.searchForm.date[0]) ? state.searchForm.date[0] : null,
        createTimeMax: (state.searchForm.date && state.searchForm.date[1]) ? state.searchForm.date[1] : null,
        orderBy: 'id desc',
      }
      api.settleImportDown({ ...obj, responseType: "blob" }).then(res => {
        const _fileName = decodeURIComponent(res.headers['content-disposition'].split(';')[1].split('=')[1])
        BlobDownLoad(res, _fileName)
      }).catch(err => {
        console.log('err', err)
      })
    }

    const getSettleImportList = () => {
      const obj = {
        page: 1,
        size: 10,
        "action": "",
        "recordId": "",
        "recordStatus": "1,2",
        orderBy: 'id desc',
      }
      api.settleImportList(obj).then(res => {
        if (res.data.list && res.data.list[0]) {
          getSettleImportResult(res.data.list[0].recordId)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    const getSettleImportResult = (recordId) => {
      state.importResult = []
      api.settleImportResult({ recordId }).then(res => {
        state.importResult.push(res.data)

        if (res.data.recordStatus == 1) {
          setTimeout(() => {
            getSettleImportResult(recordId)
          }, 5000)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    const handleSettleImportSubmit = (type) => {
      if (!state.importResult.length) {
        errorDeal('请先导入文件！')
        return
      }
      let json = {
        "recordId": state.importResult[0].recordId,
        "type": type
      }
      api.settleImportSubmit(json).then(res => {
        successDeal('操作成功！')
        state.importResult = []
        resetHandle()
      })
    }

    const pageJump = (path, data) => {
      router.push({
        path,
        query: {
          recordId: data.recordId,
          fileName: data.fileName
        }
      })
    }

    onMounted(() => {
      let winHeight = getWindowWidthAndHeight()
      state.tableHeight = winHeight.windowHeight - 330
      state.searchForm.shopName = route.query.shopName || null
      setIsDetail()
      getTableData()
      getSettleImportList()
    })

    return {
      ...toRefs(state),
      uploadRef,
      exportHandle,
      handleCurrentChange,
      handleSizeChange,
      searchHandle,
      resetHandle,
      getDateTime,
      handleSelectionChange,
      importSuccess,
      importHandle,
      handleUploadCancel,
      handleSettleImportSubmit,
      pageJump,
    }
  }
}
  </script>
  
<style lang="scss" scoped>
.content-box {
  height: 100%;
  overflow: hidden;
  overflow-y: auto;
  box-sizing: border-box;
  padding: 20px;
  .title-box {
    display: flex;
    align-items: center;
    > .title {
      font-size: 16px;
      font-weight: bold;
    }
  }
  .my-search-box {
    box-sizing: border-box;
    padding: 20px 20px 20px 0;
    padding-bottom: 0;
    font-size: 14px;
    display: flex;
    align-items: center;
    gap: 10px;

    > div {
      width: 350px;
      display: flex;
      align-items: center;

      > span {
        flex-shrink: 0;
        width: 90px;
        text-align: right;
      }
    }

    .datebox {
      width: 450px;
    }
  }
  .table-box {
    margin-top: 10px;
    .my-table-footer {
      display: flex;
      align-items: center;
      margin-top: 10px;
      flex-wrap: wrap;
      gap: 10px;
    }
  }
}

.oStatus {
  display: flex;
  align-items: center;
  gap: 5px;
  &::before {
    content: "";
    display: block;
    width: 8px;
    height: 8px;
    border-radius: 50%;
    flex-shrink: 0;
  }
}
.oStatus1 {
  &::before {
    background-color: #e6a23c;
  }
}
.oStatus2 {
  &::before {
    background-color: #b7b9bd;
  }
}
.oStatus3 {
  &::before {
    background-color: #f04134;
  }
}
.oStatus4 {
  &::before {
    background-color: #00a854;
  }
}
.oStatus5 {
  &::before {
    background-color: #e6a23c;
  }
}
</style>